import axios, { AxiosRequestConfig } from 'axios';
import { message } from 'antd';

// 创建axios实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_API_URL || '/api/pc',
    timeout: parseInt(import.meta.env.VITE_APP_TIMEOUT) || 40000,
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Connection': 'Keep-Alive',
        'Content-Type': 'application/json; charset=utf-8'
    }
});

// 请求拦截器
service.interceptors.request.use(
    (config) => {
        const token = localStorage.getItem('token');
        if (token) {
            // 使用标准的 Authorization 头设置 token
            config.headers['Authorization'] = `Bearer ${token}`;
            // 同时也设置可能需要的自定义 token 头
            config.headers['access-token'] = token;
        }
        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截器
service.interceptors.response.use(
    (response) => {
        const code = response.data.code;
        if (code === 100) {
            // Token过期或无效
            localStorage.removeItem('token');
            window.location.href = '/login';
            message.error('登录已过期，请重新登录');
        } else if (code === 1) {
            // 业务错误
            message.warning(response.data.msg);
        }
        return response;
    },
    (error) => {
        message.error('网络错误，请稍后重试');
        return Promise.reject(error);
    }
);

// 封装请求方法
const request = async <T = any>(config: AxiosRequestConfig): Promise<T> => {
    try {
        const { data } = await service(config);
        return data;
    } catch (error) {
        throw error;
    }
};

export default request;